package org.jtb.mensawotd;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.json.JSONException;
import org.json.JSONObject;

class HistoryItem implements Comparable<HistoryItem> {
	private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
	"EEE, MMM d");

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((word == null) ? 0 : word.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		HistoryItem other = (HistoryItem) obj;
		if (word == null) {
			if (other.word != null)
				return false;
		} else if (!word.equals(other.word))
			return false;
		return true;
	}

	private String word;
	private String url;
	private long time;
	
	HistoryItem(String word, String url, long time) {
		this.word = word;
		this.url = url;
		this.time = time;
	}

	String getWord() {
		return word;
	}

	public int compareTo(HistoryItem other) {
		if (this.time > other.time) {
			return -1;
		} else if (other.time > this.time) {
			return 1;
		}
		return 0;
	}

	String getUrl() {
		return url;
	}

	long getTime() {
		return time;
	}
	
	String getDateString(boolean fuzzy) {
		if (fuzzy) {
			Calendar now = Calendar.getInstance();
			Calendar then = Calendar.getInstance();
			then.setTime(new Date(time));
			Calendar yest = Calendar.getInstance();
			yest.add(Calendar.DAY_OF_YEAR, -1);

			int nowDay = now.get(Calendar.DAY_OF_YEAR);
			int thenDay = then.get(Calendar.DAY_OF_YEAR);
			int yestDay = yest.get(Calendar.DAY_OF_YEAR);
			
			if (thenDay == nowDay) {
				return "Today";
			}
			if (thenDay == yestDay) {
				return "Yesterday";
			}
		}
		return DATE_FORMAT.format(new Date(time));
	}
	
	JSONObject toJSONObject() throws JSONException {
		JSONObject jo = new JSONObject();
		jo.put("word", word);
		jo.put("url", url);
		jo.put("time", time);
		
		return jo;
	}
}
